<?php
// +----------------------------------------------------------------------
// | Author: wyd 2025/11/2
// | DESC: 
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace Study\swoole\pool;

use Swoole\Coroutine\Channel;

abstract class DbPool
{
    private $max;
    private $min;
    private $conns;

    //连接数量
    private int $count;

    abstract public function newDb();

    public function __construct($min = 5, $max = 10)
    {
        $this->min = $min;
        $this->max = $max;
        $this->conns = new Channel($this->max);
    }


    //根据最小链接数，初始化池；
    public function initPool()
    {
        for ($i = 0; $i < $this->min; $i++) {
            $this->conns->push($this->newDb());
        }
    }

    //取出
    public function getConnection()
    {
        if($this->count<$this->max){
            $this->addPool();
        }else{
            echo '没货了'.PHP_EOL;
            return $this->conns->pop(5);
        }
        return $this->conns->pop();
    }

    
    /**
     * 添加到链接池
     * @return void
     */
    public function addPool()
    {
        try {
            //先++，new的时候会导致协程
            $this->count++;
            $db = $this->db();
            $this->conns->push($db);
        } catch (\Exception $e) {
            $this->count--;
        }
    }

    //放回channel中；
    public function close($conn)
    {
        $this->conns->push($conn);
    }

}